package edu.whu.Zengqm.edu.whu;

import edu.whu.Zengqm.InitMethod;
import sun.security.jca.GetInstance;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Properties;

public class Main {
    public static Class<?> getClassFromProperties() {
        Properties p = new Properties();
        String className;
        try (InputStream propsInput = Main.class.getResourceAsStream("/app.properties")) {
            p.load(propsInput);
            className = p.getProperty("bootstrapClass");
        } catch (IOException e) {
            throw new RuntimeException("加载文件异常", e);
        }

        if (className == null) {
            throw new RuntimeException("未找到对应字段");
        }

        Class<?> targetClass;
        try {
            targetClass = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("未找到对应类", e);
        }

        return targetClass;
    }

    public static Method[] getAnnotatedMethods(Class<?> targetClass) {
        ArrayList<Method> methodArrayList = new ArrayList<>();

        for (Method method: targetClass.getMethods()) {
            if (method.isAnnotationPresent(InitMethod.class)) {
                method.setAccessible(true);
                methodArrayList.add(method);
            }
        }

        return methodArrayList.toArray(new Method[0]);
    }

    public static void main(String[] args) {
        Class<?> targetClass = getClassFromProperties();

        Method[] methods = getAnnotatedMethods(targetClass);

        Object targetInstance;
        try {
            targetInstance = targetClass.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("创建对象失败", e);
        }

        for (Method method: methods) {
            try {
                method.invoke(targetInstance);
            } catch (Exception e) {
                throw new RuntimeException("执行方法失败" + method, e);
            }
        }
    }
}
